package com.example.demo.controller;


import com.example.demo.annoation.Log;
import com.example.demo.bean.AjaxRes;
import com.example.demo.bean.SysJob;
import com.example.demo.dto.task.SysJobPageReqVO;
import com.example.demo.enums.BusinessType;
import com.example.demo.exception.TaskException;
import com.example.demo.service.ISysJobService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequestMapping(value = "/monitor/sys_job")
@RestController
public class SysJobController extends BaseAdminController {

    @Resource
    private ISysJobService sysJobService;

    @GetMapping(value = "/list")
    public AjaxRes list(SysJobPageReqVO sysJobPageReqVO) {
        return AjaxRes.success(sysJobService.list(sysJobPageReqVO));
    }

    @Log(title = "修改任务状态", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/changeStatus")
    public AjaxRes changeStatus(@RequestBody SysJob sysJob) throws SchedulerException {
        return AjaxRes.success(sysJobService.changeStatus(sysJob));
    }

    @Log(title = "新增任务", businessType = BusinessType.INSERT)
    @PostMapping(value = "/insert")
    public AjaxRes insert(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
        return AjaxRes.success(sysJobService.insert(sysJob));
    }

    @Log(title = "修改任务", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update")
    public AjaxRes update(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
        return AjaxRes.success(sysJobService.update(sysJob));
    }

    @GetMapping("/{jobId}")
    public AjaxRes query(@PathVariable("jobId") Long jobId) {
        return AjaxRes.success(sysJobService.getSysJob(new SysJob().setJobId(jobId)));
    }

    @DeleteMapping("/delete/{jobIds}")
    @Log(title = "删除定时任务", businessType = BusinessType.DELETE)
    public AjaxRes delete(@PathVariable("jobIds") Long[] jobIds) throws SchedulerException {
        return AjaxRes.success(sysJobService.deleteSysJob(jobIds));
    }

    @PutMapping("/run")
    @Log(title = "立即执行任务", businessType = BusinessType.UPDATE)
    public AjaxRes run(@RequestBody SysJob sysJob) throws SchedulerException {
        return sysJobService.run(sysJob) ? success() : error("任务不存在或已过期!");
    }
}
